<template>
  <el-dialog
    class="kw-editor"
    title="管理筛选词"
    :visible="showEditor"
    width="80%"
    :before-close="onClose"
  >
    <el-row :style="{ margin: '10px 0', lineHeight: '40px' }">
      <el-col :span="2" :style="{ fontSize: '16px' }">
        <span>新增</span>
      </el-col>
      <el-col :span="4">
        <el-select
          v-model="inputCate"
          size="small"
          filterable
          allow-create
          placeholder="选择或新建分类"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="8" :offset="1">
        <el-input
          v-model="inputList"
          size="small"
          clearable
          placeholder="输入筛选词，支持多个，使用空格分隔"
        ></el-input>
      </el-col>
      <el-col :span="2" :offset="1">
        <el-button size="small" type="primary" @click="onAddCate"
          >添加</el-button
        >
      </el-col>
    </el-row>

    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item title="当前已使用（不在常用列表中）" name="0">
        <el-button
          v-for="item in activeList"
          :key="item"
          type="primary"
          size="small"
          >{{ item }}</el-button
        >
      </el-collapse-item>
      <el-collapse-item
        v-for="(cat, index) in cate"
        :key="cat.title + index"
        :title="cat.title"
        :name="`${index + 1}`"
      >
        <div>
          <el-button size="small" type="priamry">重命名</el-button>
        </div>
        <el-checkbox-group v-model="cat.checkList">
          <el-checkbox
            v-for="item in cat.kws"
            :key="item"
            :label="item"
          ></el-checkbox>
        </el-checkbox-group>
      </el-collapse-item>
    </el-collapse>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onEdit">
        <span v-if="!isEditMode">进入编辑模式</span>
        <span v-else>退出编辑模式</span>
      </el-button>
      <el-button type="danger" @click="onDelete" :disabled="!isEditMode"
        >删除选中</el-button
      >
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onConfirm" :disabled="isEditMode"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'keyword-editor',
  props: {
    kwForm: { type: Object, require: true },
    showEditor: { type: Boolean },
    activeType: { type: String }
  },
  data() {
    return {
      activeNames: ['0', '1', '2', '3', '4'],
      cate: [
        {
          title: '通用',
          kws: ['手机壳', '卡通', '潮流', '可爱'],
          checkList: []
        },
        {
          title: '苹果',
          kws: ['se2', 'iphone11', '11pro', 'iphone12', '12pro', '12promax'],
          checkList: []
        },
        {
          title: '华为',
          kws: ['p30', 'p40', 'mate30', 'mate40', 'nova7', 'nova8'],
          checkList: []
        },
        {
          title: 'oppo',
          kws: ['reno4', 'reno5'],
          checkList: []
        }
      ],
      inputCate: '',
      inputList: '',
      isEditMode: false
    }
  },
  mounted() {
    this.filterCheckList()
  },
  computed: {
    ...mapGetters(['kwLength']),
    activeList() {
      return this.activeType === 'include'
        ? this.filterActiveList(this.kwForm.kwInclude)
        : this.activeType === 'includeAnd'
        ? this.filterActiveList(this.kwForm.kwIncludeAnd)
        : this.filterActiveList(this.kwForm.kwExclude)
    },
    cateList() {
      return this.cate.map(v => v.title)
    },
    newList() {
      return this.inputList
        .trim()
        .split(' ')
        .filter(Boolean)
    },
    options() {
      return this.cate.map(v => {
        return {
          label: v.title,
          value: v.title
        }
      })
    }
  },
  methods: {
    initCheckList() {
      // this.cate =
    },
    onClose() {
      this.$emit('update:showEditor', false)
      // 清空所有选中
      this.cate.forEach(v => (v.checkList = []))
    },
    onDelete() {
      this.$confirm('此操作将永久删除选中筛选词, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          for (const item of this.cate) {
            if (item.checkList.length) {
              item.kws = item.kws.filter(v => !item.checkList.includes(v))
              item.checkList = []
            }
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    onConfirm() {
      const list = this.updateActiveList()
      if (this.activeType === 'include') {
        this.kwForm.kwInclude = list
      } else if (this.activeType === 'includeAnd') {
        this.kwForm.kwIncludeAnd = list
      } else if (this.activeType === 'exclude') {
        this.kwForm.kwExclude = list
      }
      this.$emit('update:showEditor', false)
    },
    onEdit() {
      this.isEditMode = !this.isEditMode
    },
    handleChange(val) {
      console.log(val)
    },
    onAddCate() {
      const cate = this.inputCate.trim()
      const index = this.cateList.indexOf(cate)
      if (index > -1) {
        let item = this.cate[index]
        const count = item.kws.length + this.newList.length
        item.kws = [...new Set(item.kws.concat(this.newList))]
        if (count > item.kws.length) {
          this.$message({
            type: 'info',
            message: '监测到您添加了重复的筛选词，已为您自动过滤。'
          })
        } else {
          this.$message({
            type: 'success',
            message: `操作成功：本次添加 ${this.newList.length} 个筛选词。`
          })
        }
      } else {
        this.cate.push({
          title: cate,
          kws: this.newList,
          checkList: []
        })
      }
    },
    updateActiveList() {
      let res = this.activeList
      for (const item of this.cate) {
        res.push(...item.checkList)
      }

      return [...new Set(res)]
    },
    filterActiveList(list) {
      return list.filter(v => {
        for (const item of this.cate) {
          if (item.kws.includes(v)) return false
        }
        return true
      })
    },
    filterCheckList() {
      // 勾选已选筛选词
      const kw =
        this.activeType === 'include'
          ? this.kwForm.kwInclude
          : this.activeType === 'includeAnd'
          ? this.kwForm.kwIncludeAnd
          : this.kwForm.kwExclude
      for (const item of this.cate) {
        for (const temp of kw) {
          if (item.kws.includes(temp)) {
            item.checkList.push(temp)
          }
        }
      }
    }
  },
  watch: {
    activeList() {
      this.filterCheckList()
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__body {
  padding: 0 20px !important;
}
</style>
